"""
name: 案例2 自定义信号及使用 实例
version: 1.0
"""
import sys

from PyQt5.QtCore import pyqtSignal, QObject, pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton


class SignalObj(QObject):
    msg_err = pyqtSignal()  #不带参数
    msg_err_with_info = pyqtSignal(str)  #带str类型参数
    # 带不同类型的参数（重载）
    msg_sended = pyqtSignal(['QString'], [int], name='msgSended')

    def msg_emit(self):
        self.msg_sended['QString'].emit('hello')
        self.msg_sended[int].emit(999)

    def something_err(self):
        self.msg_err.emit()  #不带参数直接发送
        self.msg_err_with_info.emit('错误信息')#发送时必须带参数

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('自定义事件')
        self.resize(500, 300)
        self.btn = QPushButton('发射信号', self)
        self.btn.setGeometry(20, 30, 120, 40)
        self.btn2 = QPushButton('发现错误', self)
        self.btn2.setGeometry(20, 100, 120, 40)
        # 系统中自带的事件与槽函数建立连接
        self.btn.clicked.connect(self.btn_hand)
        self.btn2.clicked.connect(self.err)
        self.send = SignalObj()
        # 将自定义的信号与槽建立关联
        self.send.msg_sended['QString'].connect(self.slot_hand)
        self.send.msg_sended[int].connect(self.slot_hand2)
        self.send.msg_err.connect(self.slot_err)
        
    def btn_hand(self):
        self.send.msg_emit()
        
    def err(self):
        self.send.something_err()
        
    @pyqtSlot('QString')
    def slot_hand(self, msg):
        print('我接收到字符串: ', msg)

    @pyqtSlot('int')    
    def slot_hand2(self, msg):
        print('我接收到整数: ', msg)

    def slot_err(self):
        print('出错了，要退出！！')
        self.close()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

